package com.example.sportplay.controller;

import com.alibaba.fastjson.JSON;
import com.example.sportplay.bean.QueryInfo;
import com.example.sportplay.bean.User;
import com.example.sportplay.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserDao userDao;

    // 1、在bean层创建完QueryInfo实体之后
    // 2、编写查询逻辑
    @RequestMapping("/alluser")
    public String getUserList(QueryInfo queryInfo) {
        // 模糊查询 获取最大列表数
        int numbers = userDao.getUserCounts("%"+queryInfo.getQuery()+"%");
        // 要查出我们是从那个页面开始的, 根据页面显示内容。
        // (当前页的编号 - 1) * 每页最大数
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();

        // 查询userlist本身
        List<User> user = userDao.getAllUser("%" + queryInfo.getQuery() + "%", pageStart, queryInfo.getPageSize());

        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers", numbers); // 最大列数
        res.put("data", user);

        return JSON.toJSONString(res);
    }

    @RequestMapping("/userstate")
    // 页面将给我传过来一个id信息
    public String updateUserState(@RequestParam("id")Integer id,
                                  @RequestParam("state") Boolean state) {
        int i = userDao.updateState(id, state);
        return i > 0 ? "success": "error";
    }

    @RequestMapping("/adduser")
    // 添加用户
    public String addUser(@RequestBody User user) {
        user.setRole("普通用户");
        user.setState(false);   // 设置权限
        int i = userDao.addUser(user);
        return i > 0 ? "success": "error";
    }

    // 删除用户
    @RequestMapping("/deleteuser")
    public String deleteUser(int id) {
        int i = userDao.deleteUser(id);
        return i > 0 ? "success": "error";
    }

    // 获取当前用户信息
    @RequestMapping("/getupdateuser")
    public String getUpdateUser(int id){
        User user = userDao.getUpdateUser(id);
        String string = JSON.toJSONString(user);
        return string;
    }

    // 修改用户信息
    @RequestMapping("/edituser")
    public String editUser(@RequestBody User user){
        int i = userDao.editUser(user);
        return i > 0 ? "success": "error";
    }
}
